<template>
  <view class="register-container">
    <view class="tab-container" :data-active-tab="currentTab">
      <view
        class="tab-item"
        :class="{ active: currentTab === 'personal' }"
        @click="switchTab('personal')"
      >
        个人注册
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'company' }"
        @click="switchTab('company')"
      >
        公司注册
      </view>
      <view class="tab-indicator"></view>
    </view>

    <view class="tab-content">
      <view v-show="currentTab === 'personal'" class="tab-pane">
        <view class="form-item">
          <uni-icons
            type="person-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <input
            class="form-input"
            type="number"
            placeholder="请输入账号"
            :value="personalForm.phone"
            @input="onPhoneInput('personal', $event)"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons
            type="locked-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <input
            class="form-input"
            type="password"
            placeholder="请输入密码"
            v-model="personalForm.password"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons type="contact" size="20" class="form-icon"></uni-icons>
          <input
            class="form-input"
            type="text"
            placeholder="请输入真实姓名"
            v-model="personalForm.realName"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
    <uni-icons type="wallet-filled" size="20" class="form-icon"></uni-icons>
    <input class="form-input secure-text" type="text" placeholder="请输入身份证号" v-model="personalForm.idCard" maxlength="18" @input="onIdCardInput('personal', $event)" @blur="onIdCardBlur('personal', $event)" />
  </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons type="star-filled" size="20" class="form-icon"></uni-icons>
          <input
            class="form-input"
            type="text"
            placeholder="请输入特长技能"
            v-model="personalForm.skills"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons
            type="calendar-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <picker
            mode="selector"
            style="width: 100%"
            :range="statusOptions"
            @change="onStatusChange"
          >
            <view class="picker form-input picker-input">
              {{
                personalForm.status
                  ? statusOptions[personalForm.status]
                  : "请选择现状"
              }}
            </view>
          </picker>
        </view>
        <view class="divider"></view>
        <view class="form-item radio-form-item">
          <uni-icons type="help-filled" size="20" class="form-icon"></uni-icons>
          <view class="radio-group">
            <radio-group
              @change="onVeteranChange"
              style="width: 100%; display: flex; align-items: center"
            >
              <label class="radio-label">
                <radio
                  value="yes"
                  :checked="personalForm.isVeteran === 'yes'"
                />
                <text>是</text>
              </label>
              <label class="radio-label">
                <radio value="no" :checked="personalForm.isVeteran === 'no'" />
                <text>否</text>
              </label>
              <text class="veteran-text">（是否为退伍军人）</text>
            </radio-group>
          </view>
        </view>
        <view class="divider"></view>
        <view class="form-item" v-if="personalForm.isVeteran === 'yes'">
          <uni-icons
            type="calendar-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <picker
            mode="date"
            @change="onDischargeDateChange"
            style="width: 100%"
          >
            <view class="picker form-input picker-input">
              {{
                personalForm.dischargeDate
                  ? personalForm.dischargeDate
                  : "请选择退伍日期"
              }}
            </view>
          </picker>
        </view>
      </view>

      <view v-show="currentTab === 'company'" class="tab-pane">
        <view class="form-item">
          <uni-icons
            type="person-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <input
            class="form-input"
            type="number"
            placeholder="请输入法人手机号"
            :value="companyForm.legalPhone"
            @input="onPhoneInput('company', $event)"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons
            type="locked-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <input
            class="form-input"
            type="password"
            placeholder="请输入密码"
            v-model="companyForm.password"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons type="contact" size="20" class="form-icon"></uni-icons>
          <input
            class="form-input"
            type="text"
            placeholder="请输入法人姓名"
            v-model="companyForm.legalName"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
    <uni-icons type="wallet-filled" size="20" class="form-icon"></uni-icons>
    <input class="form-input secure-text" type="text" placeholder="请输入法人身份证号" v-model="companyForm.legalIdCard" maxlength="18" @input="onIdCardInput('company', $event)" @blur="onIdCardBlur('company', $event)" />
  </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons type="home-filled" size="20" class="form-icon"></uni-icons>
          <input
            class="form-input"
            type="text"
            placeholder="请输入公司名称"
            v-model="companyForm.companyName"
          />
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons
            type="calendar-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <picker
            mode="selector"
            style="width: 100%"
            :range="companyTypeOptions"
            @change="onCompanyTypeChange"
          >
            <view class="picker form-input picker-input">
              {{
                companyForm.companyType
                  ? companyTypeOptions[companyForm.companyType]
                  : "请选择类型"
              }}
            </view>
          </picker>
        </view>
        <view class="divider"></view>
        <view class="form-item">
          <uni-icons
            type="image-filled"
            size="20"
            class="form-icon"
          ></uni-icons>
          <view class="upload-container">
            <view class="upload-area" @click="chooseImage">
              <view
                v-if="!companyForm.businessLicense"
                class="upload-placeholder"
              >
                <view class="upload-icon">+</view>
                <text>点击上传图片</text>
              </view>
              <image
                v-else
                :src="companyForm.businessLicense"
                class="uploaded-image"
                mode="aspectFill"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>

    <button class="register-button" @click="handleRegister">注册</button>
  </view>
</template>

<script>
import uniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import { authAPI } from '@/static/indexAPI.js';
import config from '../../static/config.js';

export default {
  components: {
    uniIcons,
  },
  data() {
    return {
      currentTab: "personal", // 默认显示个人注册
      statusOptions: ["老板", "员工", "个体户", "自由职业者", "其他"],
      companyTypeOptions: ["美食", "娱乐", "住宿", "游玩"],
      personalForm: {
        phone: "",
        password: "",
        confirmPassword: "",
        realName: "",
        idCard: "",
        skills: "",
        status: null,
        isVeteran: null, // 'yes' 或 'no'
        dischargeDate: "",
      },
      companyForm: {
        companyName: "",
        legalName: "",
        legalIdCard: "",
        legalPhone: "",
        password: "",
        confirmPassword: "",
        companyType: null,
        businessLicense: "", // 存储图片路径
      },
    };
  },
  methods: {
    switchTab(tab) {
      this.currentTab = tab;
    },

    // 现状选择变化
    onStatusChange(e) {
      this.personalForm.status = e.detail.value;
    },

    // 公司类型选择变化
    onCompanyTypeChange(e) {
      this.companyForm.companyType = e.detail.value;
    },

    // 退伍军人选项变化
    onVeteranChange(e) {
      this.personalForm.isVeteran = e.detail.value;
    },

    // 退伍日期选择变化
    onDischargeDateChange(e) {
      this.personalForm.dischargeDate = e.detail.value;
    },

    // 监听手机号输入
    onPhoneInput(type, e) {
      // 获取输入的值
      let value = e.detail.value;

      // 只允许输入数字
      value = value.replace(/[^\d]/g, "");

      // 限制长度为11位
      if (value.length > 11) {
        value = value.substring(0, 11);
      }

      // 更新对应的数据
      if (type === "personal") {
        this.personalForm.phone = value;
      } else if (type === "company") {
        this.companyForm.legalPhone = value;
      }
    },

    // 监听身份证号输入
    onIdCardInput(type, e) {
      // 获取输入的值
      let value = e.detail.value;

      // 过滤掉所有非数字和非X的字符
      let filteredValue = '';
      for (let i = 0; i < value.length; i++) {
        const char = value.charAt(i);
        // 前17位只能是数字
        if (filteredValue.length < 17) {
          if (/[0-9]/.test(char)) {
            filteredValue += char;
          }
        } 
        // 第18位可以是数字或X
        else if (filteredValue.length === 17) {
          if (/[0-9Xx]/.test(char)) {
            filteredValue += char.toUpperCase();
          }
        }
      }

      // 确保不超过18位
      if (filteredValue.length > 18) {
        filteredValue = filteredValue.substring(0, 18);
      }

      // 更新对应的数据
      if (type === 'personal') {
        this.personalForm.idCard = filteredValue;
      } else if (type === 'company') {
        this.companyForm.legalIdCard = filteredValue;
      }
    },

    // 身份证号输入框失去焦点时的处理
    onIdCardBlur(type, e) {
      // 获取输入框的值
      let value = e.detail.value;
      
      // 清除所有非数字和非X的字符
      let cleanedValue = '';
      for (let i = 0; i < value.length; i++) {
        const char = value.charAt(i);
        // 前17位只能是数字
        if (cleanedValue.length < 17) {
          if (/[0-9]/.test(char)) {
            cleanedValue += char;
          }
        } 
        // 第18位可以是数字或X
        else if (cleanedValue.length === 17) {
          if (/[0-9Xx]/.test(char)) {
            cleanedValue += char.toUpperCase();
          }
        }
      }
      
      // 确保不超过18位
      if (cleanedValue.length > 18) {
        cleanedValue = cleanedValue.substring(0, 18);
      }
      
      // 更新对应的数据
      if (type === 'personal') {
        this.personalForm.idCard = cleanedValue;
      } else if (type === 'company') {
        this.companyForm.legalIdCard = cleanedValue;
      }
    },

    // 身份证号按键按下处理
    onIdCardKeydown(e) {
      const key = e.key;

      // 允许的控制键
      const controlKeys = [
        "Backspace",
        "Delete",
        "ArrowLeft",
        "ArrowRight",
        "ArrowUp",
        "ArrowDown",
        "Tab",
        "Enter",
        "Home",
        "End",
      ];

      // 如果是控制键，允许操作
      if (controlKeys.includes(key)) {
        return;
      }

      // 获取当前输入框的值和光标位置
      const input = e.target || e.srcElement;
      const value = input.value || "";
      const selectionStart = input.selectionStart || 0;

      // 判断当前光标位置应该允许输入什么字符
      let isValid = false;

      // 如果光标在前17位位置
      if (selectionStart < 17) {
        // 前17位只能是数字
        isValid = /^[0-9]$/.test(key);
      }
      // 如果光标在第18位位置
      else if (selectionStart === 17) {
        // 第18位可以是数字或X
        isValid = /^[0-9Xx]$/.test(key);
      }

      // 如果输入不合法，则阻止默认行为
      if (!isValid) {
        e.preventDefault();
        return false;
      }
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.companyForm.businessLicense = res.tempFilePaths[0];
        },
      });
    },

    // 上传图片到服务器
    async uploadImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: config.baseURL + "/api/common/upload",
          filePath: filePath,
          name: "file",
          header: {
            Accept: "application/json",
          },
          success: (uploadFileRes) => {
            try {
              const data = JSON.parse(uploadFileRes.data);
              if (data.code === 1) {
                resolve(data.data.url); // 返回服务器上的图片URL
              } else {
                reject(new Error(data.msg || "上传失败"));
              }
            } catch (error) {
              reject(error);
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    // 验证手机号格式
    isValidPhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phone);
    },

    // 验证身份证号格式
    isValidIdCard(idCard) {
      const idCardRegex =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      return idCardRegex.test(idCard);
    },

    // 处理注册
    handleRegister() {
      if (this.currentTab === "personal") {
        this.handlePersonalRegister();
      } else {
        this.handleCompanyRegister();
      }
    },

    // 个人注册
			async handlePersonalRegister() {
				// 验证手机号
				if (!this.personalForm.phone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.isValidPhone(this.personalForm.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				// 验证密码
				if (!this.personalForm.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}
				
				// 验证真实姓名
				if (!this.personalForm.realName) {
					uni.showToast({
						title: '请输入真实姓名',
						icon: 'none'
					});
					return;
				}
				
				// 验证身份证号
				if (!this.personalForm.idCard) {
					uni.showToast({
						title: '请输入身份证号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.isValidIdCard(this.personalForm.idCard)) {
					uni.showToast({
						title: '请输入正确的身份证号',
						icon: 'none'
					});
					return;
				}
				
				// 验证特长技能
				if (!this.personalForm.skills) {
					uni.showToast({
						title: '请输入特长技能',
						icon: 'none'
					});
					return;
				}
				
				// 验证现状
				if (this.personalForm.status === null) {
					uni.showToast({
						title: '请选择现状',
						icon: 'none'
					});
					return;
				}
				
				// 验证是否为退伍军人
				if (this.personalForm.isVeteran === null) {
					uni.showToast({
						title: '请选择是否为退伍军人',
						icon: 'none'
					});
					return;
				}
				
				// 如果是退伍军人，验证退伍日期
				if (this.personalForm.isVeteran === 'yes' && !this.personalForm.dischargeDate) {
					uni.showToast({
						title: '请选择退伍日期',
						icon: 'none'
					});
					return;
				}
				
				// 准备发送到接口的数据
				const requestData = {
					username: this.personalForm.phone,
					password: this.personalForm.password,
					name: this.personalForm.realName,
					idcard: this.personalForm.idCard,
					status_quo: String(Number(this.personalForm.status) + 1), // 转换为1-5的值
					retired: this.personalForm.isVeteran === 'yes' ? '1' : '0'
				};
				
				// 只有当用户是退伍军人时才添加退伍日期字段
				if (this.personalForm.isVeteran === 'yes') {
					requestData.retired_date = this.personalForm.dischargeDate;
				}
				
				requestData.specialties = this.personalForm.skills;
				
				// 调用个人注册接口
				try {
					const res = await authAPI.registerPerson(requestData);
					
					if (res.data.code === 1) {
						uni.showToast({
							title: '个人注册成功',
							icon: 'success'
						});
						
						// 存储用户信息并跳转到首页
						const userinfo = {
							username: this.personalForm.phone,
							realName: this.personalForm.realName,
							type: 'personal'
						};
						
						uni.setStorageSync('userinfo', userinfo);
						
						// 跳转到首页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1000);
					} else if (res.data.code === 0 || res.code === 0) {
						uni.showToast({
							title: res.data.message || '注册失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			},
			
			// 公司注册
			async handleCompanyRegister() {
				// 验证公司名称
				if (!this.companyForm.companyName) {
					uni.showToast({
						title: '请输入公司名称',
						icon: 'none'
					});
					return;
				}
				
				// 验证法人姓名
				if (!this.companyForm.legalName) {
					uni.showToast({
						title: '请输入法人姓名',
						icon: 'none'
					});
					return;
				}
				
				// 验证法人身份证号
				if (!this.companyForm.legalIdCard) {
					uni.showToast({
						title: '请输入法人身份证号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.isValidIdCard(this.companyForm.legalIdCard)) {
					uni.showToast({
						title: '请输入正确的法人身份证号',
						icon: 'none'
					});
					return;
				}
				
				// 验证法人手机号
				if (!this.companyForm.legalPhone) {
					uni.showToast({
						title: '请输入法人手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.isValidPhone(this.companyForm.legalPhone)) {
					uni.showToast({
						title: '请输入正确的法人手机号',
						icon: 'none'
					});
					return;
				}
				
				// 验证密码
				if (!this.companyForm.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}
				
				// 准备发送到接口的数据
				const requestData = {
					username: this.companyForm.legalPhone,
					password: this.companyForm.password,
					company_name: this.companyForm.companyName,
					legal_person: this.companyForm.legalName,
					idcard: this.companyForm.legalIdCard,
					phone: this.companyForm.legalPhone
				};
				
				// 调用公司注册接口
				try {
					const res = await authAPI.registerCompany(requestData);
					
					if (res.data.code === 1) {
						uni.showToast({
							title: '公司注册成功',
							icon: 'success'
						});
						
						// 存储用户信息并跳转到首页
						const userinfo = {
							username: this.companyForm.legalPhone,
							companyName: this.companyForm.companyName,
							type: 'company'
						};
						
						uni.setStorageSync('userinfo', userinfo);
						
						// 跳转到首页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1000);
					} else {
						uni.showToast({
							title: res.data.message || '注册失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped>
.register-container {
  padding: 20rpx;
  background-color: #fff;
  min-height: 94vh;
  display: flex;
  flex-direction: column;
}

.tab-container {
  display: flex;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #fff;
  border-radius: 10rpx;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #999;
  cursor: pointer;
  transition: color 0.3s ease;
  z-index: 2;
}

.tab-item.active {
  color: #2f2f2f;
  font-weight: bold;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  height: 4rpx;
  width: 16%;
  background-color: #2f2f2f;
  left: 18%;
  transition: left 0.3s ease;
  z-index: 1;
}

.tab-container[data-active-tab="company"] .tab-indicator {
  left: 67%;
}

.tab-content {
  flex: 1;
  padding: 20rpx 0 40rpx;
  overflow: hidden;
}

.tab-pane {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 40rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  max-height: calc(100vh - 200rpx);
}

.form-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  color: #2f2f2f;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
}

.radio-form-item {
  align-items: flex-start;
}

.form-icon {
  margin-right: 20rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05) inset;
}

.picker-input {
  display: flex;
  align-items: center;
  color: #999;
  width: 100%;
}

.picker-input:after {
  content: "";
  width: 20rpx;
  height: 20rpx;
  border-right: 2px solid #999;
  border-bottom: 2px solid #999;
  transform: rotate(45deg);
  margin-left: auto;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.radio-group {
  flex: 1;
}

.radio-label {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
}

.radio-label radio {
  margin-right: 10rpx;
  transform: scale(0.7);
}

.veteran-text {
  color: #777777;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.register-button {
  width: 70%;
  height: 94rpx;
  background-color: #2f2f2f;
  color: #fff;
  border-radius: 30rpx;
  font-size: 34rpx;
  border: none;
  margin-top: 20rpx;
  flex-shrink: 0;
  align-self: center;
}

/* 上传图片样式 */
.upload-container {
  flex: 1;
}

.upload-area {
  height: 100rpx;
  border: 1rpx dashed #ddd;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  cursor: pointer;
  width: 26%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 20rpx;
}

.secure-text {
  -webkit-text-security: none; /* 尝试禁用密码点 */
}

.upload-icon {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 20rpx 0;
}
</style>
